package org.akomantoso.core.io.util.group;

import java.io.IOException;
import java.util.IdentityHashMap;
import java.util.List;
import java.util.Map;

import org.akomantoso.core.data.Block;
import org.akomantoso.core.data.group.BlockElements;
import org.akomantoso.core.io.Input;
import org.akomantoso.core.io.InputConstants;
import org.akomantoso.core.io.util.Instantiator;
import org.akomantoso.core.util.MapUtil;

/**
 * @author <a href="mailto:jacques.militello@gmail.com">Jacques Militello</a>
 */
public final class BlockElementsGroup {

	private BlockElementsGroup() {
	}

	public static final Map<String, Instantiator<BlockElements>> MAP;

	public static BlockElements instantiate(String elementName) {

		final Instantiator<BlockElements> instatiator = MAP.get(elementName);
		if (instatiator == null) {
			throw new RuntimeException("Tag [" + elementName + "] not supported ?!?");
		}
		return instatiator.instantiate();

	}
	
	public static void read(Input in,List<BlockElements> elements, final String localName) throws IOException {
		BlockElements blockElement = null;
		int eventType = in.getEventType();
		while(true) {
			switch (eventType) {
			case InputConstants.START_ELEMENT:
				elements.add(blockElement = BlockElementsGroup.instantiate(in.getLocalName()));
				blockElement.readExternal(in);
				break;			
			case InputConstants.END_ELEMENT:
				if (localName == in.getLocalName()) {
					return;
				} 
			}
			eventType = in.readNext();
		}
	}

	static {
		
		Map<String, Instantiator<BlockElements>> temp = new IdentityHashMap<String, Instantiator<BlockElements>>();
		
		MapUtil.copy(HTMLBlockGroup.MAP, temp);
		MapUtil.copy(ANblockGroup.MAP, temp);
		
		// block
		temp.put(Block.ELEMENT.intern(), new Instantiator<BlockElements>() {
			public Block instantiate() {
				return new Block();
			}
		});
		
		MAP = temp;

	}
}
